#include "core/stockcontroller.h"
#include "core/stockmodel.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

StockController::StockController(QObject *parent) :
    BaseController(parent)
{
}

/**
  Returns all stocks, regardless of the kind of item that they are.
  This method is currently unnecessary, and is left with a bare
  implementation.
  */
QList<BaseModel *> StockController::getAll()
{
    QList<BaseModel *> list;
    StockModel *stock;
    QSqlQuery query;
    QString sql = "SELECT s.ID, s.serial, transactionID, actualSellingPrice "
            "FROM Stocks;";

    emit update(list);
    return list;
}

/**
  Gets the stocks of the specified item. Fires the update() signal,
  so any connected views will be notified.
  */
QList<BaseModel *> StockController::getStocksOf(ItemModel *item)
{
    QList<BaseModel *> list;
    StockModel *stock;
    QSqlQuery query;
    bool ok;
    QString serial;

    // TODO: Fix this query - see workaround below for details
    QString sql = "SELECT s.ID, s.serial, s.transactionID, s.actualSellingPrice "
            "FROM Items AS i LEFT OUTER JOIN Stocks AS s ON i.ID = s.itemID "
            "WHERE i.ID = :ID";

    query.prepare(sql);
    query.bindValue(":ID", item->getID());

    ok = query.exec();
    if (!ok) {
        /* TODO: Print detailed error information here */
        qDebug() << "StockController::getStocksOf(): Query failed!" << query.lastError().text();
    }

    while (query.next()) {
        stock = new StockModel;

        // The SQL query above gives a record with an empty serial if no stocks for the
        // specified item exist.
        serial = query.value(1).toString();
        if (serial == "") {
            break;
        }

        stock->setID(query.value(0).toInt());
        stock->setSerial(query.value(1).toString());
        stock->setItem(item);
        stock->setTransactionId(query.value(2).toInt());

        list.append(stock);
    }

    emit update(list);
    return list;
}

/**
  Adds a new Stock to the database.

  NOTE: This disregards the Stock's sell price and transaction ID
  properties, and assumes that stocks that are just being added have
  not already been sold.
  */
void StockController::addStock(StockModel *stock)
{
    QSqlQuery query;
    QString sql = "INSERT INTO Stocks "
            "(itemID, serial) VALUES"
            "(:itemID, :serial);";
    bool ok;

    // Let's assume that stocks that are just being added have not already been sold
    query.prepare(sql);
    query.bindValue(":itemID", stock->getItem()->getID());
    query.bindValue(":serial", stock->getSerial());
    ok = query.exec();

    if (!ok) {
        qDebug() << "StockController: Add stock failed: " << query.lastError().text();
    }
}
